package com.kunchi.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kunchi.platform.service.LoginService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

/**
 * Created by denniszhou on 2017/6/19.
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {

  private static Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

  @Value("${baseUrl}")
  private String baseUrl;

  @Value("${login.name}")
  private String loginName;

  @Value("${login.password}")
  private String loginPassword;

  @Value("${login.hash}")
  private String loginHash;

  @Value("${rent.login.tenantename}")
  private String rentLoginTenanteName;

  @Value("${rent.login.name}")
  private String rentLoginName;

  @Value("${rent.login.password}")
  private String rentLoginPassword;

  @Value("${rent.login.hash}")
  private String rentLoginHash;

  @Autowired
  RestTemplate restTemplate;

  @Override
  public String login() {
    String url = baseUrl + "/user/login";
    JSONObject account = new JSONObject();
    account.put("name", loginName);
    account.put("password", loginPassword);
    account.put("hash", loginHash);
    String response = restTemplate.postForObject(MessageFormat.format(
        url, loginName, loginPassword, loginHash), account, String.class);
    return JSONObject.parseObject(response).getString("data");
  }

  @Override
  public String rentLogin() {
    String url = baseUrl + "/user/getToken";
    JSONObject account = new JSONObject();
    account.put("tenantEname", rentLoginTenanteName);
    account.put("name", rentLoginName);
    account.put("password", rentLoginPassword);
    account.put("hash", rentLoginHash);
    String response = restTemplate.postForObject(MessageFormat.format(
        url, rentLoginTenanteName, rentLoginName, rentLoginPassword, rentLoginHash),
        account, String.class);
    return JSONObject.parseObject(response).getString("data");
  }
}
